package com.lb.shopguide.ui.fragment.boss;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.shop.StoreBean;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.ui.view.chart.LbBarView;
import com.lb.shopguide.ui.view.chart.LbCircleView;
import com.lb.shopguide.ui.view.chart.LbLineView;
import com.lb.shopguide.ui.view.chart.entity.PerformanceBean;
import com.lb.shopguide.ui.view.chart.entity.StoreMemberChartBean;
import com.lb.shopguide.ui.view.chart.entity.StoreSaleDataBean;
import com.lb.shopguide.ui.view.chart.entity.StoreStaffSaleBean;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.ChartUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2018/1/2.
 */

public class FragmentStoreDataDetail extends BaseCommonFragment {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.iv_shop_logo)
    ImageView ivShopLogo;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shop_phone)
    TextView tvShopPhone;
    @BindView(R.id.tv_shop_addr)
    TextView tvShopAddr;
    @BindView(R.id.tv_increase_percent_last_month)
    TextView tvIncreasePercentLastMonth;
    @BindView(R.id.tv_increase_percent_last_year)
    TextView tvIncreasePercentLastYear;
    @BindView(R.id.tv_all_member_count)
    TextView tvAllMemberCount;
    @BindView(R.id.tv_new_member_count)
    TextView tvNewMemberCount;
    @BindView(R.id.tv_guide_num)
    TextView tvGuideNum;
    @BindView(R.id.tv_manager_num)
    TextView tvManagerNum;
    @BindView(R.id.chart_line_sale)
    LbLineView lineChartSale;
    @BindView(R.id.chart_line_guide)
    LbLineView lineChartStaffPerformance;
    @BindView(R.id.chart_pie_member)
    LbCircleView pieChartMember;
    @BindView(R.id.layout_pie_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.layout_barchart)
    LbBarView layoutBarchart;

    private StoreBean storeBean;



    public static FragmentStoreDataDetail newInstance(StoreBean storeBean) {
        FragmentStoreDataDetail fragmentStoreDetail = new FragmentStoreDataDetail();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.STORE_BEAN, storeBean);
        fragmentStoreDetail.setArguments(bundle);
        return fragmentStoreDetail;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_store_data_detail;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.STORE_BEAN)) {
            storeBean = (StoreBean) bundle.getSerializable(AppConstant.STORE_BEAN);
        }
        if (storeBean != null) {
            initRequest();
        }
    }

    @Override
    public void initView() {
        ctb.setLeftImageSrc(R.drawable.iv_boss_back);
        ctb.setLeftText("门店详情");
        bindStoreInfo();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentStoreDataDetail.class.getName();
    }

    private void initRequest() {
        sendRequestGetSaleCountData();
        sendRequestGetMoneyData();
        sendRequestGetMemberData();
    }

    private void bindStoreInfo() {
        tvShopName.setText(storeBean.getStoreName());
        tvShopPhone.setText(storeBean.getMobileNum());
        tvShopAddr.setText(storeBean.getConnectAddress());
        ImageLoaderUtils.getGlideManager().asBitmap().load(storeBean.getStoreLogoUrl()).apply(ImageLoaderUtils.getSGCommonGlideOption(12)).into(ivShopLogo);
    }

    private void sendRequestGetSaleCountData() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        StoreSaleDataBean storeSaleDataBean = JsonUtil.getGson().fromJson(jsonObject.getString("storeSaleCountData"), StoreSaleDataBean.class);
                        bindSaleData(storeSaleDataBean);
                        StoreStaffSaleBean storeStaffSaleBean = JsonUtil.getGson().fromJson(jsonObject.getString("storeStaffSaleCountData"), StoreStaffSaleBean.class);
                        bindStaffData(storeStaffSaleBean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getMerStoreSaleCountData(new SimpleLbObserver(listener, otherListener), storeBean.getStoreCode(),this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetMoneyData() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        PerformanceBean moneyPerformance = JsonUtil.getGson().fromJson(jsonObject.getString("storeMoneyCountData"), PerformanceBean.class);
                        bindFinanceData(moneyPerformance);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getStoreMoneyCountData(new SimpleLbObserver(listener, otherListener), storeBean.getStoreCode(),this,FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetMemberData() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    StoreMemberChartBean storeMemberChartBean = (StoreMemberChartBean) JsonUtil.getObject(response.getReturnContent(), StoreMemberChartBean.class);
                    bindMemberData(storeMemberChartBean);
                }
            }
        };
        ApiMethodBoss.getStoreMemberData(new SimpleLbObserver(listener, otherListener), storeBean.getStoreCode(),this,FragmentEvent.DESTROY_VIEW);
    }

    private void bindSaleData(StoreSaleDataBean bean) {
        if (bean.getCompareLastYearPercent() != null) {
            tvIncreasePercentLastYear.setText("同比上年增长：" + bean.getCompareLastYearPercent());
        } else {
            tvIncreasePercentLastYear.setText("同比上年增长：--");
        }
        if (bean.getCompareLastMonthPercent() != null) {
            tvIncreasePercentLastMonth.setText("同比上月增长：" + bean.getCompareLastMonthPercent());
        } else {
            tvIncreasePercentLastMonth.setText("同比上月增长：--");
        }
        bindChartSale(bean.getStoreSaleCountData());
    }

    private void bindMemberData(StoreMemberChartBean bean) {
        tvAllMemberCount.setText("会员总数：" + bean.getTotalMemberNum());
        tvNewMemberCount.setText("本月新增会员：" + bean.getCurNewMonthMemberNum());
        int[] colors = {Color.parseColor("#ff6c6c"), Color.parseColor("#94cdff"), Color.parseColor("#e9e9e9")};
        if (ChartUtil.bindPieChartInShop(pieChartMember, bean.getMemberScale(), colors)) {
            pieChartMember.setVisibility(View.VISIBLE);
            layoutEmpty.setVisibility(View.GONE);
        } else {
            layoutEmpty.setVisibility(View.VISIBLE);
            pieChartMember.setVisibility(View.GONE);
        }
    }

    private void bindStaffData(StoreStaffSaleBean bean) {
        tvGuideNum.setText("导购总数：" + bean.getShopGuideCount() + "人");
        tvManagerNum.setText("店长总数" + bean.getShopOwnerCount() + "人");
        bindChartStaff(bean.getStoreStaffSaleCountData());
    }

    private void bindChartSale(PerformanceBean bean) {
        ChartUtil.bindLineChart(lineChartSale, bean);
    }

    private void bindChartStaff(PerformanceBean bean) {
        ChartUtil.bindLineChart(lineChartStaffPerformance, bean);
    }

    private void bindFinanceData(PerformanceBean bean) {
        ChartUtil.bindBarChart(layoutBarchart, bean);
    }

    @OnClick(R.id.image_left)
    void leftClick() {
        pop();
    }
}
